package leetcode;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class LeetCode139 {

    boolean result = false;

    List<String> wordDict;

    String s;

    //动态规划 递归会超时
    public boolean wordBreak1(String s, List<String> wordDict) {
        this.wordDict = wordDict;
        this.s = s;
        helper(0);
        return result;
    }

    private void helper(int index) {
        if (index == s.length()) {
            result = true;
        } else if (index < s.length()) {
            int lastLength = s.length() - index;
            for (String str : wordDict) {
                int length = str.length();
                if (lastLength >= length && s.substring(index, index + length).equals(str)) {
                    helper(index + length);
                }
            }
        }
    }

    //------------------------------------------------------------------
    public boolean wordBreak2(String s, List<String> wordDict) {
        int n = wordDict.size();
        int[][] dp = new int[n][n];
        return false;
    }

    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> wordDictSet = new HashSet(wordDict);
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && wordDictSet.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }

}
